
package com.jf.cloud.leaf.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import com.jf.cloud.api.leaf.dto.SegmentDTO;
import com.jf.cloud.api.leaf.dto.SegmentItemDTO;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.leaf.common.Result;
import com.jf.cloud.leaf.common.Status;
import com.jf.cloud.leaf.exception.LeafServerException;
import com.jf.cloud.leaf.exception.NoKeyException;
import com.jf.cloud.leaf.service.SegmentService;
import com.jf.cloud.leaf.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Hidden;

import java.util.*;


/**
 * @author zz
 * @date 2020/7/15
 */
@RestController
@Hidden
public class SegmentFeignController implements SegmentFeignClient {

    /**
     * 标准日期时间格式，精确到秒：yyyy-MM-dd HH:mm:ss
     */
    public static final String DATETIME_PATTERN = "yyMMdd";

    public static final FastDateFormat DATETIME_FORMAT = FastDateFormat.getInstance(DATETIME_PATTERN);

    public static final Integer USER_SPLIT_LENGTH = 3;

    @Autowired
    private SegmentService segmentService;

    @Override
    public ServerResponseEntity<Long> getSegmentId(String key) {
        Long nextId = get(key, segmentService.getId(key));
        // 默认我们给个12位
        return ServerResponseEntity.success(NumberUtil.genNo(nextId, 12));
    }

    @Override
    public ServerResponseEntity<List<Long>> batchGetSegmentId(String key, Integer size) {
        if (Objects.isNull(size) || size < 1) {
            return ServerResponseEntity.success(new ArrayList<>());
        }
        ArrayList<Long> segmentIds = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            segmentIds.add(get(key, segmentService.getId(key)));
        }
        return ServerResponseEntity.success(segmentIds);
    }

    @Override
    public ServerResponseEntity<List<Long>> batchGetUserId(String key, Integer size) {
        if (Objects.isNull(size) || size < 1) {
            return ServerResponseEntity.success(new ArrayList<>());
        }
        ArrayList<Long> segmentIds = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            segmentIds.add(NumberUtil.genNo(get(key, segmentService.getId(key)), 12));
        }
        return ServerResponseEntity.success(segmentIds);
    }

    @Override
    public ServerResponseEntity<Long> getSegmentIdWithDateTime(String key, Long userId) {
        return ServerResponseEntity.success(createSegmentIdWithDateTime(key, userId));
    }


    @Override
    public ServerResponseEntity<Map<String, List<Long>>> batchSegmentIdWithDateTime(SegmentDTO segmentDTO) {
        if (CollUtil.isEmpty(segmentDTO.getSegmentItemList())) {
            throw new LuckException("segmentItemList没有数据");
        }
        Map<String, List<Long>> map = new HashMap<>(segmentDTO.getSegmentItemList().size());
        for (SegmentItemDTO segmentItem : segmentDTO.getSegmentItemList()) {
            map.put(segmentItem.getKey(), listSegmentIdWithDateTime(segmentDTO.getId(), segmentItem));
        }
        return ServerResponseEntity.success(map);
    }

    public List<Long> listSegmentIdWithDateTime(Long id, SegmentItemDTO segmentItem) {
        if (Objects.isNull(id)) {
            throw new LuckException("id不能为空");
        }
        List<Long> ids = new ArrayList<>();
        if (Objects.isNull(segmentItem.getCount()) || segmentItem.getCount() < 1) {
            return ids;
        }
        for (int i = 0; i < segmentItem.getCount(); i++) {
            ids.add(createSegmentIdWithDateTime(segmentItem.getKey(), id));
        }

        return ids;
    }

    private Long createSegmentIdWithDateTime(String key, Long userId) {
        Long nextId = get(key, segmentService.getId(key));
        // 默认生成转换为16位长度的id，js long的精度是16位的，所以默认我们也给个16位 6 + 7 + 最后3位是userId这很关键
        return Long.valueOf(getDateTime() + NumberUtil.genNo(nextId, 7) + getUserIdKey(String.valueOf(userId)));
    }


    private Long get(String key, Result id) {
        Result result;
        if (key == null || key.isEmpty()) {
            throw new NoKeyException();
        }
        result = id;
        if (Objects.equals(result.getStatus(), Status.EXCEPTION)) {
            throw new LeafServerException(result.toString());
        }
        return result.getId();
    }


    private String getDateTime() {
        return DateUtil.format(new Date(), DATETIME_FORMAT);
    }

    /**
     * 截取用户ID的后三位
     */
    private String getUserIdKey(String userId) {
        // 如果userId的长度大于或等于3，则直接返回
        if (userId.length() >= USER_SPLIT_LENGTH) {
            return userId.substring(userId.length() - USER_SPLIT_LENGTH);
        }

        // 如果userId的长度大于或等于3，则直接前面补0
        StringBuilder userIdKey = new StringBuilder(userId);
        while (userIdKey.length() != USER_SPLIT_LENGTH) {
            userIdKey.insert(0, "0");
        }
        return userIdKey.toString();
    }
}
